package MyThread;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: AliceMana
 * Date: 2023-01-04
 * Time: 17:09
 */

// 自己实现一个阻塞队列
class MyBlockingQueue {
    private int[] items = new int[1000];
    private int head;
    private int tail;
    private int size;

    // 入队列
    public void put(int num) throws InterruptedException {
        synchronized (this) {
            while (size == items.length) {
                // return;
                // 实现阻塞功能
                this.wait();
            }
            items[tail] = num;
            tail++;
            if (tail >= items.length) {
                tail = 0;
            }
            size++;

            // 这个 notify 唤醒 take 中的 wait();
            this.notify();
        }
    }

    // 出队列
    public Integer take() throws InterruptedException {
        int res = 0;
        synchronized (this) {
            while (size == 0) {
                // return null;
                this.wait();
            }
            res = items[head];
            head++;
            if (head >= items.length) {
                head = 0;
            }
            size--;

            // 这个 notify 唤醒 put 中的wait();
            this.notify();
        }
        return res;
    }
}
public class ThreadDemo23 {
    public static void main(String[] args) {
        // 用工厂模式测试

        MyBlockingQueue myBlockingQueue = new MyBlockingQueue();

        Thread consumer = new Thread(() -> {
            while (true) {
                try {
                    int res = myBlockingQueue.take();
                    System.out.println("消费者: " + res);
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        consumer.start();

        Thread producer = new Thread(() -> {
           int count = 0;
           while (true) {
               try {
                   myBlockingQueue.put(count);
                   System.out.println("生产者: " + count);
                   count++;
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
        });
        producer.start();
    }
}
